package com.web.server.common.filters;

import com.web.server.common.cache.RedisHelper;
import com.web.server.common.exception.CrmException;
import com.web.server.common.exception.StatusCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by ZHANGXIANLIANG1 on 2016/1/18.
 */
public class SessionCheckInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        String sessionId = request.getParameter("JSESSIONID");
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            // 如果目标方法需要检查Session，则到Redis服务器取Session
            SessionCheck sessionCheck = ((HandlerMethod) handler).getMethod().getAnnotation(SessionCheck.class);
            SessionCheck typeSessionCheck = ((HandlerMethod) handler).getBeanType().getAnnotation(SessionCheck.class);
            //处理表示 SessionCheck validate false  的情况  不做验证
            if (null != sessionCheck && !sessionCheck.validate()) {
                return true;
            }
            if(null != typeSessionCheck && !typeSessionCheck.validate()){
                return true;
            }

            // 检查SESSION ID
            if (StringUtils.isEmpty(sessionId)) {
                throw new CrmException(StatusCode.STATUS_FAILURE, "SESSION无效，请重新登陆");
            }

            // 检查用户是否登录
            String userId = RedisHelper.getInstance().getValue(sessionId);
            if (StringUtils.isBlank(userId)) {
                throw new CrmException(StatusCode.STATUS_FAILURE, "SESSION无效，请重新登陆");
            }
        }

        return true;
    }
}
